package com.qf.gateway.service;

import cn.hutool.core.thread.ThreadUtil;
import com.qf.common.bean.R;
import com.qf.common.dto.TenantDto;
import com.qf.common.model.QfTenant;
import com.qf.gateway.feign.TenantFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

/**
 * @author 千锋健哥
 */
@Service
public class AuthServiceImpl implements AuthService{

    @Autowired
    private TenantFeign tenantFeign;


    @Override
    public Boolean findByAccessKey(String accessKey, String accessSecurit) {
        //1. 根据accessKey到数据库获取租户对象
        TenantDto dto  = new TenantDto();
        dto.setAccessKey(accessKey);
        /**
         * 2. gateway网关中不支持feign远程调用, 所以下面只能用异步调用
         * 多线程异步调用
         */
        R<List<QfTenant>> result = null;

        try {
            result = ThreadUtil.execAsync(new Callable<R<List<QfTenant>>>() {
                @Override
                public R<List<QfTenant>> call() throws Exception {
                    R<List<QfTenant>> result = tenantFeign.findTenantAll(dto);
                    return result;
                }
            }).get();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //3. 根据异步远程调用结果判断秘钥是否正确
        if (result != null) {
            if (result.getData() != null && result.getData().size() > 0) {
                QfTenant tenant = result.getData().get(0);
                if (tenant.getAccessSecurit().equals(accessSecurit)) {
                    return true;
                }
            }
        }
        return false;
    }

}
